$(function() {
	ajaxGetHot5();
	$('#blog-tag-input').keydown(function(e){
		var code = e.which;
		if(code == 13) {
			var temp = $('#blog-tag-input').val();
			if(addTag(temp)) {
				$('#blog-tag-input').val("");
			}
		}
    });
});

function ajaxGetHot5() {
	$.ajax({
		url: rootPath + "/blog/tag/hot5",
		type: "post",
		dataType: "json",
		success: ajaxGetHot5_back
	});
}

function ajaxGetHot5_back(res) {
	var htmlStr = "";
	if(res.result == JS_AJAX_SUCCESS) {
		$.each(res.btdList, function() {
			htmlStr += "<a href='javascript:(0)' class='hotLabel fleft' onclick='addHotTagToBlog(this)'>"+this.tagname+"</a>";
		});
	} else {
		alert(res.msg);
		htmlStr = "加载失败";
	}
	$("#blog-tag-hot").append(htmlStr);
}

function ajaxPublish() {
	var title = $("#blog-title").val();
	var content = $("#blog-content").val();
	var tag = $("#blog-tag-my-input").val();
	if(isEmpty(title)) {
		$("#blog-title").focus();
		alert("标题不能为空");
		return;
	}
	if(isEmpty(content)) {
		$("#blog-content").focus();
		alert("内容不能为空");
		return;
	}
	if(isEmpty(tag)) {
		alert("标签不能为空");
		return;
	}
	var dt = {
		title: title,
		content: content,
		tag: tag
	};
	$.ajax({
		url: rootPath + "/blog/publish",
		type: "post",
		dataType: "json",
		data: dt,
		success: ajaxPublish_back
	});
}

function ajaxPublish_back(res) {
	if(res.result == JS_AJAX_SUCCESS) {
		alert("发表成功");
		location.href=rootPath + "/blog/index";
	} else {
		alert(res.msg);
	}
}

function addHotTagToBlog(o) {
	var newTag = $(o).html();
	if(isEmpty(newTag)) {
		return;
	}
	addTag(newTag);
}


function addTag(newTag) {
	var str = $('#blog-tag-my-input').val();
	var strArr = str.split(",");
	if (strArr.length != 5) {
		var isOk = contain(str, newTag);
		if (isOk) {
			alert("不能重复添加");
			return false;
		} else {
			var temp = pinjie(str, newTag, ",");
			$('#blog-tag-my-input').val(temp);
			var htmlStr = "";
			htmlStr += "<div class='myLabel fleft' tagname='" + newTag + "'>" + newTag + "<a href='javascript:(0)' onclick='deleteTag(this)'>x</a></div>";
			$('#blog-tag-my').append(htmlStr);
			return true;
		}
	} else {
		alert("标签最多5个");
		return false;
	}
}

function deleteTag(o) {
	var str = $(o).parent().attr("tagname");
	var str2 = $('#blog-tag-my-input').val();
	var temp = deleteStr(str2, str);
	$('#blog-tag-my-input').val(temp);
	$(o).parent().remove();
}